package com.yunwaikeji.gy_tool_library.utils;

import android.app.Activity;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Stack;

/**
 * 栈工具
 */
public class GYStackActivityUtils {
    private static GYStackActivityUtils gyStackActivityUtils;
    private Stack<WeakReference<Activity>> weakReferenceStack;

    public static GYStackActivityUtils getInstance() {
        if (gyStackActivityUtils == null) {
            synchronized (GYStackActivityUtils.class) {
                if (gyStackActivityUtils == null) {
                    gyStackActivityUtils = new GYStackActivityUtils();
                }
            }
        }
        return gyStackActivityUtils;
    }

    /**
     * 添加Activity到栈
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (weakReferenceStack == null) {
            weakReferenceStack = new Stack<>();
        }
        weakReferenceStack.add(new WeakReference<>(activity));
    }

    /**
     * 检查弱引用是否释放，若释放，则从栈中清理掉该元素
     */
    public void checkWeakReference() {
        if (weakReferenceStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = weakReferenceStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                if (temp == null) {
                    it.remove();
                }
            }
        }
    }

    /**
     * 获取当前Activity（栈中最后一个压入的）
     *
     * @return
     */
    public Activity lastActivity() {
        checkWeakReference();
        if (weakReferenceStack != null && !weakReferenceStack.isEmpty()) {
            return weakReferenceStack.lastElement().get();
        }
        return null;
    }

    /**
     * 关闭当前Activity（栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = lastActivity();
        if (activity != null) {
            finishActivity(activity);
        }
    }

    /**
     * 关闭指定的Activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null && weakReferenceStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = weakReferenceStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                // 清理掉已经释放的activity
                if (temp == null) {
                    it.remove();
                    continue;
                }
                if (temp == activity) {
                    it.remove();
                }
            }
            activity.finish();
        }
    }

    /**
     * 关闭指定类名的所有Activity
     *
     * @param activityName
     */
    public void finishActivity(String activityName) {
        if (weakReferenceStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> weakReferenceIterator = weakReferenceStack.iterator(); weakReferenceIterator.hasNext(); ) {
                WeakReference<Activity> activityReference = weakReferenceIterator.next();
                Activity activity = activityReference.get();
                // 清理掉已经释放的activity
                if (activity == null) {
                    weakReferenceIterator.remove();
                    continue;
                }
                if (activity.getClass().getName().equals(activityName)) {
                    weakReferenceIterator.remove();
                    activity.finish();
                }
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        if (weakReferenceStack != null) {
            for (WeakReference<Activity> activityReference : weakReferenceStack) {
                Activity activity = activityReference.get();
                if (activity != null) {
                    activity.finish();
                }
            }
            weakReferenceStack.clear();
        }
    }

    /**
     * 关闭应用程序
     */
    public void finishApp() {
        try {
            finishAllActivity();
            // 退出JVM,释放所占内存资源,0表示正常退出
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
